/**
 * @Project Name :  als-rpc-client
 * @Package Name :  com.alvis
 * @Description :  TODO
 * @author :  Alvis
 * @Creation Date:  2018-07-03 4:49 PM
 * @ModificationHistory Who    When    What
 * --------  ---------  --------------------------
 */
package com.alvis.container;

import com.alvis.registry.zookeeper.RegisterManager;
import com.alvis.transfer.RpcResponse;
import com.alvis.utilities.ClassHelper;
import com.alvis.transfer.RpcClient;
import com.alvis.transfer.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author :  Alvis
 * @Description :  TODO
 * @Creation Date:  2018-07-03 4:49 PM
 */
public class RpcServiceProxy implements InvocationHandler {

    public RpcServiceProxy(Class<?> targetClass) {
        this.targetClass = targetClass;
    }

    private Class<?> targetClass;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        RpcRequest rpcRequest = getRpcRequest(method, args);
        String serverNode = RegisterManager.getZkServiceNode().getRandomService(rpcRequest.getServiceName());
        String[] hostPort = serverNode.split(":");
        RpcClient client = new RpcClient(hostPort[0], Integer.parseInt(hostPort[1]));
        RpcResponse response = client.request(rpcRequest);
        return response.getResponse();
    }


    private RpcRequest getRpcRequest(Method method, Object[] args) {
        RpcService rpcService = (RpcService) targetClass.getAnnotations()[0];
        String serviceName = rpcService.value();
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setServiceName(serviceName);
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameterTypes(method.getParameterTypes());
        rpcRequest.setArgs(args);
        return rpcRequest;
    }


}
